"""Repository基类"""
from typing import Generic, TypeVar, Type, Optional, List, Dict, Any
from sqlalchemy.orm import Session
from sqlalchemy import and_
from app.database import Base

ModelType = TypeVar("ModelType", bound=Base)


class BaseRepository(Generic[ModelType]):
    """Repository基类，提供通用CRUD操作"""

    def __init__(self, model: Type[ModelType], db: Session):
        """
        初始化Repository

        Args:
            model: SQLAlchemy模型类
            db: 数据库会话
        """
        self.model = model
        self.db = db

    def get(self, id: int) -> Optional[ModelType]:
        """根据ID获取单个记录"""
        return self.db.query(self.model).filter(self.model.id == id).first()

    def get_by_field(self, field_name: str, value: Any) -> Optional[ModelType]:
        """根据字段值获取单个记录"""
        return self.db.query(self.model).filter(getattr(self.model, field_name) == value).first()

    def get_all(
        self,
        skip: int = 0,
        limit: int = 100,
        filters: Optional[Dict[str, Any]] = None,
        order_by: Optional[str] = None,
    ) -> List[ModelType]:
        """
        获取记录列表

        Args:
            skip: 跳过记录数
            limit: 返回记录数
            filters: 过滤条件字典
            order_by: 排序字段（支持 desc 后缀，如 "created_at desc"）
        """
        query = self.db.query(self.model)

        # 应用过滤条件
        if filters:
            for field, value in filters.items():
                if hasattr(self.model, field):
                    query = query.filter(getattr(self.model, field) == value)

        # 应用排序
        if order_by:
            parts = order_by.split()
            field_name = parts[0]
            if len(parts) > 1 and parts[1].lower() == "desc":
                query = query.order_by(getattr(self.model, field_name).desc())
            else:
                query = query.order_by(getattr(self.model, field_name))

        return query.offset(skip).limit(limit).all()

    def count(self, filters: Optional[Dict[str, Any]] = None) -> int:
        """统计记录数"""
        query = self.db.query(self.model)

        if filters:
            for field, value in filters.items():
                if hasattr(self.model, field):
                    query = query.filter(getattr(self.model, field) == value)

        return query.count()

    def create(self, obj_in: Dict[str, Any]) -> ModelType:
        """创建新记录"""
        db_obj = self.model(**obj_in)
        self.db.add(db_obj)
        self.db.commit()
        self.db.refresh(db_obj)
        return db_obj

    def update(self, db_obj: ModelType, obj_in: Dict[str, Any]) -> ModelType:
        """更新记录"""
        for field, value in obj_in.items():
            if hasattr(db_obj, field):
                setattr(db_obj, field, value)
        self.db.commit()
        self.db.refresh(db_obj)
        return db_obj

    def delete(self, id: int) -> bool:
        """删除记录"""
        obj = self.get(id)
        if obj:
            self.db.delete(obj)
            self.db.commit()
            return True
        return False

    def bulk_create(self, objs_in: List[Dict[str, Any]]) -> List[ModelType]:
        """批量创建记录"""
        db_objs = [self.model(**obj_in) for obj_in in objs_in]
        self.db.add_all(db_objs)
        self.db.commit()
        for obj in db_objs:
            self.db.refresh(obj)
        return db_objs

